package net.sahv.bdyz.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import org.apache.commons.codec.binary.Base64;

public class SerializerUtils {
	
	/**
	 * 对象转化为字符串
	 * @param objs
	 * @return String
	 */
	public static String serializer(Object obj){
		ByteArrayOutputStream bos=new ByteArrayOutputStream(); 
		ObjectOutputStream oos=null;
		try{ 
			oos=new ObjectOutputStream(bos); 
			oos.writeObject(obj);
			byte[] tmpByte=bos.toByteArray();  
			oos.close();
			tmpByte=Base64.encodeBase64(tmpByte);
			String outStr=new String(tmpByte,"UTF-8");
			return outStr;
		}   
		catch(Exception ex){ex.printStackTrace();} 
		return "";
	}
	
    /**
     * 字符串转化为对象
     * @param str
     * @return Object
     */
	public static Object unSerializer(String str){
		ObjectInputStream ois=null;
		try{
			byte[] inByte=Base64.decodeBase64(str.getBytes("UTF-8"));
			ByteArrayInputStream bis=new ByteArrayInputStream(inByte); 
			ois=new ObjectInputStream(bis); 
			Object o=(Object)(ois.readObject()); 
			ois.close(); 
			return o;
		}
		catch(Exception ex){ex.printStackTrace();} 
		return null;
	}
	
	/*public static void main(String[] args){
		Etswjc jc=new Etswjc();
		jc.setLrdw("中国人");
		String aa=SerializerUtils.serializer(jc);
		System.out.print(aa);
		System.out.print("\n");
		Etswjc jc2=(Etswjc)SerializerUtils.unSerializer(aa);
		System.out.print(jc2.getLrdw());
	}*/
}
